import ftxClient
import timeUtil
from ciso8601 import parse_datetime
from decimal import *


def as_num(x):
    num = '{:.6f}'.format(x)  # 5f表示保留5位小数点的float型
    return num


def str2Number(strParam):
    if strParam == '' or strParam is None:
        # 遇到空字符串和None会自定义一种处理方式，这里设为默认0
        res = 0
    try:
        res = float(strParam)
    except:
        # 如果遇到了非数字字符，可以异常处理。这里设为默认为0
        res = 0
    return res


if __name__ == '__main__':
    timeUtil = timeUtil.TimeUtil()
    # utc_time = timeUtil.local_2_utc(timeUtil.get_date('2021-04-10'))
    # print(utc_time)
    # print(timeUtil.get_cur_date_date())
    # print(timeUtil.get_next_date_date())

    keyInfo = {}
    client = ftxClient.FtxClient('AUKAE1uTGtAwho6c3zsCVB311jZw3qVdrJ7UR35Q', 'gYwknqMSecSCv7tnmpXe-FviBNMUaeVtOBR-HjMf')

    future_list = client.list_futures()
    market_list = client.list_markets()
    print(len(future_list))
    print(len(market_list))
    # for future in future_list:
    #     print(future)
    #     for market in market_list:
    #        print(market)
    #        if future['type'] == '永续' and market['name'].find('/') and future['name'][0:3] == market['name'][0:3]:
    #            print('future.name:%s, market.name:%s'% (future['name'], market['name']))
    usd_list = []
    perp_list = []
    for market in market_list:
        if market['name'].endswith('/USD'):
            usd_list.append(market['name'])
        if market['name'].endswith('-PERP'):
            perp_list.append(market['name'])

    print(len(usd_list))
    print(len(perp_list))
    print(
        "================================================================================================================================================")
    match_list = []
    usd_list_filter = []
    perp_list_filter = []
    for usd in usd_list:
        for perp in perp_list:
            pre_usd = usd.split('/')[0]
            pre_perp = perp.split('-')[0]
            if pre_usd == pre_perp and pre_usd != 'USDT':
                match_list.append(pre_usd)
                usd_list_filter.append(usd)
                perp_list_filter.append(perp)
    print(
        "usd_list_filter=perp_list_filter============================================================================================")
    print(len(match_list))
    print(usd_list_filter)
    print(perp_list_filter)
    print(
        "================================================================================================================================================")
    # startTime = timeUtil.get_time_stamp_datetime('2021-04-10 17:00:00')
    # endTime = timeUtil.get_time_stamp_date(timeUtil.get_next_date_str())
    # funding_rates = client.get_funding_rates(start_time=startTime, end_time=startTime)
    # print(len(funding_rates))
    # print(
    #     "funding_rates_filter===========================================================================================================================")
    #
    # funding_rates_filter = []
    # getcontext()
    # getcontext().prec = 4
    # for fund in funding_rates:
    #     if fund['future'] in perp_list_filter:
    #         fund['rate'] = Decimal(fund['rate']) * 100
    #         funding_rates_filter.append(fund)
    #
    # funding_rates_filter.sort(key=lambda k: (k.get('rate'), 0))
    # print(funding_rates_filter)
    # print(
    #     "future_rate_volume======================================================================================================================================")
    #
    # for fund in funding_rates_filter:
    #     if str2Number(fund['rate']) > 0.001:
    #
    #         future_by_name = client.get_future_by_name(fund['future'])
    #         print(future_by_name)
    #         future_stat = client.get_future_stats(fund['future'])
    #         print(future_stat)
    #         print('future:%s, rate:%s, nextRate:%s, volume:%s, volumeUsd24H:%s' % (
    #             fund['future'], str2Number(fund['rate']), as_num(future_stat['nextFundingRate']), future_by_name['volume'],
    #             future_by_name['volumeUsd24h']
    #         ))

    print(
        "market======================================================================================================================================")

    # trade = client.get_trades(market="BTC/USD")
    # print(trade)

    print(
        "markets======================================================================================================================================")

    # market_list = client.list_markets()
    # market_BTC = client.get_markets_by_name("BTC/USD")
    # print(market_BTC)